package com.gitee.huanminabc.jcommon.str;

import com.alibaba.fastjson.JSON;

/**
 * 简要描述
 *
 * @Author: mac
 * @Date: 2025/4/3 12:35
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class StringTypeCastUtil {

    public static Object cast(String str) {
        return cast(str, StringIdentifyUtil.strType(str));
    }

    //将字符串转换为实际类型
    public static Object cast(String str, Class<?> type) {
        if (String.class.isAssignableFrom(type)) {
            return str;
        }
        if (int.class.isAssignableFrom(type) || Integer.class.isAssignableFrom(type)) {
            return Integer.parseInt(str);
        }
        if (long.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type)) {
            return Long.parseLong(str);
        }
        if (double.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type)) {
            return Double.parseDouble(str);
        }
        if (float.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type)) {
            return Float.parseFloat(str);
        }
        if (boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type)) {
            return Boolean.parseBoolean(str);
        }
        if (byte.class.isAssignableFrom(type) || Byte.class.isAssignableFrom(type)) {
            return Byte.parseByte(str);
        }
        if (short.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type)) {
            return Short.parseShort(str);
        }
        if (char.class.isAssignableFrom(type) || Character.class.isAssignableFrom(type)) {
            return str.charAt(0);
        }
        return JSON.parseObject(str, type);
    }

}
